import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { articleService, categoryService, tagService } from '../services/api';
import ArticleCard from '../components/article/ArticleCard';
import { BsArrowRight } from 'react-icons/bs';
import Spinner from '../components/common/Spinner';

const Home = () => {
  const [latestArticles, setLatestArticles] = useState([]);
  const [featuredArticles, setFeaturedArticles] = useState([]);
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        
        // 获取最新文章
        const latestRes = await articleService.getArticles(0, 6);
        setLatestArticles(latestRes.data.content);
        
        // 获取热门文章
        const featuredRes = await articleService.getArticles(0, 3, 'views', 'desc');
        setFeaturedArticles(featuredRes.data.content);
        
        // 获取分类
        const categoriesRes = await categoryService.getCategories();
        setCategories(categoriesRes.data);
        
        // 获取标签
        const tagsRes = await tagService.getTags();
        setTags(tagsRes.data);
        
        setLoading(false);
      } catch (err) {
        console.error('加载首页数据失败', err);
        setError('加载数据失败，请稍后重试');
        setLoading(false);
      }
    };
    
    fetchData();
  }, []);

  if (loading) {
    return <Spinner />;
  }

  if (error) {
    return (
      <div className="text-center py-10">
        <h2 className="text-2xl text-red-500 mb-4">{error}</h2>
        <button
          onClick={() => window.location.reload()}
          className="btn btn-primary"
        >
          重新加载
        </button>
      </div>
    );
  }

  return (
    <div>
      {/* 英雄区 */}
      <section className="bg-gradient-to-r from-primary-600 to-secondary-600 text-white rounded-lg p-8 mb-12">
        <div className="max-w-3xl mx-auto text-center">
          <h1 className="text-4xl md:text-5xl font-bold mb-4">Java程序员的知识分享平台</h1>
          <p className="text-lg md:text-xl mb-6">
            探索Java生态系统的最新技术、最佳实践和创新思想
          </p>
          <div className="flex justify-center space-x-4">
            <Link to="/articles" className="btn bg-white text-primary-600 hover:bg-gray-100">
              浏览文章
            </Link>
            <Link to="/register" className="btn bg-transparent border border-white hover:bg-white/10">
              立即加入
            </Link>
          </div>
        </div>
      </section>

      {/* 最新文章 */}
      <section className="mb-12">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-dark-800 dark:text-dark-200">最新文章</h2>
          <Link to="/articles" className="text-primary-600 dark:text-primary-400 flex items-center hover:underline">
            查看更多 <BsArrowRight className="ml-1" />
          </Link>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {latestArticles.map(article => (
            <ArticleCard key={article.id} article={article} />
          ))}
        </div>
      </section>

      {/* 热门文章和侧边栏 */}
      <section className="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-12">
        <div className="lg:col-span-2">
          <h2 className="text-2xl font-bold text-dark-800 dark:text-dark-200 mb-6">热门文章</h2>
          <div className="space-y-6">
            {featuredArticles.map(article => (
              <div key={article.id} className="card p-6">
                <h3 className="text-xl font-semibold mb-2">
                  <Link to={`/articles/${article.id}`} className="text-dark-800 dark:text-dark-200 hover:text-primary-600 dark:hover:text-primary-400">
                    {article.title}
                  </Link>
                </h3>
                <p className="text-dark-600 dark:text-dark-300 mb-4">
                  {article.content.substring(0, 150)}...
                </p>
                <div className="flex justify-between items-center text-sm text-dark-500 dark:text-dark-400">
                  <span>作者: {article.author.username}</span>
                  <div className="flex items-center space-x-4">
                    <span>{article.views} 阅读</span>
                    <span>{article.likes} 赞</span>
                    <span>{article.commentCount} 评论</span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
        
        <div className="lg:col-span-1 space-y-8">
          {/* 分类 */}
          <div className="card p-6">
            <h3 className="text-xl font-semibold text-dark-800 dark:text-dark-200 mb-4">分类</h3>
            <ul className="space-y-2">
              {categories.slice(0, 5).map(category => (
                <li key={category.id}>
                  <Link
                    to={`/categories/${category.id}`}
                    className="flex justify-between items-center text-dark-600 dark:text-dark-300 hover:text-primary-600 dark:hover:text-primary-400"
                  >
                    <span>{category.name}</span>
                    <span className="bg-primary-100 dark:bg-primary-900 text-primary-800 dark:text-primary-200 text-sm px-2 py-1 rounded-full">
                      {category.articleCount}
                    </span>
                  </Link>
                </li>
              ))}
            </ul>
            <Link
              to="/categories"
              className="mt-4 inline-block text-primary-600 dark:text-primary-400 hover:underline"
            >
              查看所有分类
            </Link>
          </div>
          
          {/* 标签 */}
          <div className="card p-6">
            <h3 className="text-xl font-semibold text-dark-800 dark:text-dark-200 mb-4">标签</h3>
            <div className="flex flex-wrap gap-2">
              {tags.slice(0, 10).map(tag => (
                <Link
                  key={tag.id}
                  to={`/tags/${tag.id}`}
                  className="bg-gray-100 dark:bg-dark-700 text-dark-600 dark:text-dark-300 hover:bg-primary-100 dark:hover:bg-primary-900 hover:text-primary-800 dark:hover:text-primary-200 px-3 py-1 rounded-full text-sm"
                >
                  {tag.name} ({tag.articleCount})
                </Link>
              ))}
            </div>
            <Link
              to="/tags"
              className="mt-4 inline-block text-primary-600 dark:text-primary-400 hover:underline"
            >
              查看所有标签
            </Link>
          </div>
        </div>
      </section>
    </div>
  );
};

export default Home; 